package org.example.slave.packet;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.example.slave.util.ByteUtil;

/**
 * @author dingrui
 * @since 2022/2/15
 * @description
 */

/**
 * <pre>
 * +-------+ +-------------------+ +--------+ +---------------------+ +-----------+ +---------+
 * | bytes | |         1         | |    2   | |           1         | |     5     | |    n    |
 * +-------+ +-------------------+ +--------+ +---------------------+ +-----------+ +---------+
 * |  name | | field_count(0xff) | | err_no | | sql_state_marker(#) | | sql_state | | message |
 * +-------+ +-------------------+ +--------+ +---------------------+ +-----------+ +---------+
 * </pre>
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class ErrPacket extends PacketWithHeader {

    public byte fieldCount;
    public int errorNumber;
    public byte sqlStateMarker;
    public byte[] sqlState;
    public String message;

    public ErrPacket() {
    }

    public ErrPacket(byte[] data) {
        this.fromBytes(data);
    }

    @Override
    public void fromBytes(byte[] data) {
        int index = 0;
        // 1. read field count
        this.fieldCount = data[0];
        index++;
        // 2. read error no.
        this.errorNumber = ByteUtil.readUnsignedShortLittleEndian(data, index);
        index += 2;
        // 3. read marker
        this.sqlStateMarker = data[index];
        index++;
        // 4. read sqlState
        this.sqlState = ByteUtil.readFixedLengthBytes(data, index, 5);
        index += 5;
        // 5. read message
        this.message = new String(ByteUtil.readFixedLengthBytes(data, index, data.length - index));
        // end read
    }
}
